<template>
    <el-form :model="form">
        <el-form-item label="登录账号" :label-width="formLabelWidth">
            <el-input v-model="form.adminname" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth">
            <el-input type="password" v-model="form.password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="角色" :label-width="formLabelWidth">
            <el-select v-model.number="form.role" placeholder="请选择角色">
                <el-option v-for="item in roles" v-bind:label="item.label" v-bind:value="item.value" />
            </el-select>
        </el-form-item>
        <el-form-item label="权限" :label-width="formLabelWidth">
            <!-- <el-input v-model="form.checkedKeys" autocomplete="off" /> -->
            <el-tree ref="treeRef" :data="data" show-checkbox node-key="id" >
            </el-tree>
        </el-form-item>
        <el-form-item>
            <el-button @click="addOperFn">添加</el-button>
            <el-button @click="cancelFn">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import type { IOper } from "@/myTypes"
import { addOperatorApi } from "@/api/user"
import { ElMessage, ElTree } from "element-plus";
import { roles,grantsData as data } from "./data";

interface IEmits {
    (e: "onOk"): void,
    (e: "onCancel"): void,
}
const emits = defineEmits<IEmits>()

const formLabelWidth = '140px'

const form = reactive<IOper>({
    adminname: '',
    password: "",
    role: 0,
    checkedKeys: []
})

const treeRef = ref();

const addOperFn = () => {
    console.log("form",form);
    
    // 处理树形结构中选择的key

    const keys = treeRef.value.getCheckedKeys(false).concat(treeRef.value.getHalfCheckedKeys(false));

    console.log("keys",keys);
    form.checkedKeys = keys;
    
    // 发送请求
    addOperatorApi(form)
    .then(res=>{
        if(res.data.code==="200"){
            ElMessage.success("添加成功");
        }else if(res.data.code==="10004"){
            ElMessage.error("管理员已存在");
        }
    })
    .catch(error=>{
        ElMessage.error("添加失败，服务器出错");
    })
    
}


const cancelFn = () => {
    emits("onCancel");
}


const defaultProps = {
    children: 'children',
    label: 'label',
}




</script>


<style lang="scss" scoped>
.el-select {
    width: 300px;
}

.el-input {
    width: 300px;
}

.dialog-footer button:first-child {
    margin-right: 10px;
}
</style>
